package com.qf.zuoye0620.interceptor;

import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/20 18:54
 * @Version v1.8
 **/

public class AuthInterceptor implements HandlerInterceptor {
    private static final String MERCHANT_ID_PARAM = "mch_id";
    private static final String APP_ID_PARAM = "appid";
    private static final String TOKEN_PARAM = "token";
    private static final String SIGN_PARAM = "sign";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String merchantId = request.getParameter(MERCHANT_ID_PARAM);
        String appId = request.getParameter(APP_ID_PARAM);
        String token = request.getParameter(TOKEN_PARAM);
        String sign = request.getParameter(SIGN_PARAM);

        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(appId) ||
                StringUtils.isEmpty(token) || StringUtils.isEmpty(sign)) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().println("Missing required parameters");
            return false;
        }
        // 进行签名验证
        if (!verifySign(request)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().println("Invalid signature");
            return false;
        }

        return true;
    }

    private boolean verifySign(HttpServletRequest request) {
        // TODO: 实现签名验证逻辑
        return true;
    }
}
